package com.nananren.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nananren.common.Result;
import com.nananren.domain.Book;
import com.nananren.domain.Employee;
import com.nananren.domain.OperateLog;
import com.nananren.dto.OperateLogDto;
import com.nananren.service.EmployeeService;
import com.nananren.service.OperateLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/operateLog")
public class OperateLogController {

    @Autowired
    private OperateLogService operateLogService;
    @Autowired
    private EmployeeService employeeService;

    // 日志分页条件查询
    @GetMapping("/page")
    public Result page(int page, int pageSize, String operateUser, String operateMethod, String operateClass,
                       String operateArgs, String operateReturn,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")LocalDateTime end) {
        log.info("操作日志查询：page:{}, pageSize:{}， operateUser:{}, operateMethod:{}, operateClass:{}, operateArgs:{}," +
                "operateReturn: {}, begin: {}, end: {}",
                page, pageSize, operateUser, operateMethod, operateClass, operateArgs, operateReturn, begin, end);
        Page<OperateLog> operateLogPage = new Page<>(page, pageSize);
        Page<OperateLogDto> operateLogDtoPage = new Page<>();
        // 条件构造器
        LambdaQueryWrapper<OperateLog> operateLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 操作人
        // 先根据operateUser到员工表中进行模糊查询，如果查出来数据了，获取所有id，然后到operateLog中找id相同的
        // 如果没查出来数据，直接返回空
        if (operateUser != null && operateUser != "") {
            LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            employeeLambdaQueryWrapper.like(operateUser != null, Employee::getUsername, operateUser);
            List<Employee> list = employeeService.list(employeeLambdaQueryWrapper);
            if (list.size() == 0) {
                return Result.error("暂无数据");
            }
            List<Long> ids = list.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            operateLogLambdaQueryWrapper.in(list.size() != 0, OperateLog::getOperateId, ids);
        }
        //操作方法
        operateLogLambdaQueryWrapper.like(operateMethod != null, OperateLog::getOperateMethod, operateMethod);
        // 操作类
        operateLogLambdaQueryWrapper.like(operateClass != null, OperateLog::getOperateClass, operateClass);
        // 操作方法传入的参数
        operateLogLambdaQueryWrapper.like(operateArgs != null, OperateLog::getOperateArgs, operateArgs);
        // 操作方法的返回值
        operateLogLambdaQueryWrapper.like(operateReturn != null, OperateLog::getOperateReturn, operateReturn);
        // 日期条件
        // begin等于null，end不等于null，查询borrow_time小于等于end的所有数据
        operateLogLambdaQueryWrapper.le(begin == null && end != null, OperateLog::getCreateTime, end);
        // begin不等于null，end等于null，查询borrow_time大于等于begin的所有数据
        operateLogLambdaQueryWrapper.ge(begin != null && end == null, OperateLog::getCreateTime, begin);
        // begin和end都不等于null，查询borrow_time大于等于begin并小于等于end的所有数据
        operateLogLambdaQueryWrapper.between(begin != null && end != null, OperateLog::getCreateTime, begin, end);
        // 根据操作时间倒序排序
        operateLogLambdaQueryWrapper.orderByDesc(OperateLog::getCreateTime);
        // 分页查询
        operateLogService.page(operateLogPage, operateLogLambdaQueryWrapper);

        // 对象拷贝
        BeanUtils.copyProperties(operateLogPage, operateLogDtoPage, "records");
        List<OperateLog> records = operateLogPage.getRecords();
        List<OperateLogDto> result = records.stream().map(item -> {
            OperateLogDto operateLogDto = new OperateLogDto();
            BeanUtils.copyProperties(item, operateLogDto);
            // 根据操作人id获取操作人的username
            Long operateId = item.getOperateId();// 操作人id
            Employee emp = employeeService.getById(operateId);
            if (emp != null) {
                operateLogDto.setOperateUser(emp.getUsername());
            }
            return operateLogDto;
        }).collect(Collectors.toList());

        // 给operateLogDtoPage的records复制
        operateLogDtoPage.setRecords(result);

        return operateLogDtoPage.getTotal() != 0 ? Result.success("查询成功", operateLogDtoPage) : Result.error("暂无数据");
    }

    // 删除日志
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id) {
        log.info("根据id删除日志：{}", id);
        operateLogService.removeById(id);
        return Result.success("删除成功");
    }
}
